package com.reagent.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reagent.response.Result;
import com.reagent.system.entity.User;
import com.reagent.system.mapper.UserMapper;
import com.reagent.system.service.UserService;
import com.reagent.utils.JWTUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.util.HtmlUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;


    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result logincheck(User user) {
        User userinfo = userMapper.selectOne(new QueryWrapper<User>()
                .select("*")
                .eq("username", HtmlUtils.htmlEscape(user.getUsername()))
                .eq("password", HtmlUtils.htmlEscape(user.getPassword())));
        if (!ObjectUtils.isEmpty(userinfo)) {
            //封装信息到token中
            HashMap<String, String> map = new HashMap<>();
            map.put("id", userinfo.getId().toString());
            map.put("username", userinfo.getUsername());
            map.put("rid", userinfo.getRid().toString());
            map.put("status", userinfo.getStatus().toString());
            map.put("createtime", userinfo.getCreatetime().toString());
            String token = JWTUtils.generateToken(map);
            return Result.success()
                    .message("欢迎" + userinfo.getUsername() + "!")
                    .data(token);
        }
        return Result.error().message("用户名或密码错误");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Object signInfo(User user) {
        user.setCreatetime(new Date()).setDesc("暂无用户描述").setRid(3).setStatus(1);
        int a = userMapper.insert(user);
        if (a > 0) {
            return Result.success().message("注册成功,请登录!");
        }
        return Result.error().message("注册失败,请重试!");
    }
}
